# pythonProject5/db/session.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.pool import QueuePool
from core.config import settings

# 创建数据库引擎
engine = create_engine(
    settings.DATABASE_URL,
    poolclass=QueuePool,
    pool_size=settings.DATABASE_POOL_SIZE,
    max_overflow=settings.DATABASE_MAX_OVERFLOW,
    connect_args={"check_same_thread": False, "timeout": 30},
    echo=settings.DATABASE_ECHO  # 生产关闭
)

# 会话工厂
session_factory = sessionmaker(bind=engine)
SessionLocal = scoped_session(session_factory)

# 创建基类（用于模型继承）
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

# 提供数据库会话
def get_db_session():
    """提供数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
